package com.miplus.ccrm.core.service.commission;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.miplus.ccrm.common.CmdResVo;
import com.miplus.ccrm.common.JPubUtils;
import com.miplus.ccrm.core.controller.vo.commission.*;
import com.miplus.ccrm.core.pojo.FiAgentRepayReport;
import com.miplus.ccrm.core.pojo.FiBillReport;
import com.miplus.ccrm.core.mapper.FiBillReportMapper;
import com.miplus.ccrm.core.service.ExportService;
import com.miplus.ccrm.core.service.crd.FiImportHistService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
* @author wangzl
* @description 针对表【fi_bill_report】的数据库操作Service实现
* @createDate 2025-03-11 12:03:44
*/
@Service
@Slf4j
public class FiBillReportServiceImpl extends MPJBaseServiceImpl<FiBillReportMapper, FiBillReport>
    implements FiBillReportService{

    @Resource
    private ExportService exportService;
    @Resource
    private FiImportHistService fiImportHistService;

   @Override
   public  IPage<FiBillResVo> getBillReport(FiBIllListReqVo para)
   {
       return selectJoinListPage(
               new Page<>(para.getPageNum(),para.getPageSize()),
               FiBillResVo.class,
               new MPJLambdaWrapper<FiBillReport>()
                       .in(para.getDept()!=null,FiBillReport::getDept,para.getDept())
                       .in(para.getDisttag()!=null,FiBillReport::getDisttag,para.getDisttag())
                       .gt(StringUtils.isNotEmpty(para.getStartMonth()),FiBillReport::getBillMonth,para.getStartMonth())
                       .lt(StringUtils.isNotEmpty(para.getEndMonth()),FiBillReport::getBillMonth,para.getEndMonth())
                       .eq(ObjectUtils.isNotNull(para.getBillStatus()),FiBillReport::getBillStatus,para.getBillStatus())
                       .selectAll(FiBillReport.class)
                       .selectAs("(select grpname from sys_grp where grpid = t.dept)",FiBillResVo::getDeptname)
                       .selectAs("fun_getnames('SORTING.QUEUE',t.disttag)",FiBillResVo::getDisttagdesc)
                       .selectAs("case when t.bill_status = 1 then '已结账' else '未结账' end",FiBillResVo::getBillStatusDesc)
       );
   }
   @Override
   @Transactional
   public CmdResVo billFinished(String usrid, List<Integer> reportIds)
   {
       List<FiBillReport> fiBillReportList =  baseMapper.selectList(
               new LambdaQueryWrapper<FiBillReport>()
                       .in(FiBillReport::getReportId,reportIds)
       );
       for( FiBillReport x : fiBillReportList) {
           x.setMdusr(usrid);
           x.setMddt(new Date());
           x.setBillStatus(1);
           updateById(x);
           //需要更新其他部分处。
           baseMapper.afterBillFinished(usrid, x.getBillMonth(), x.getDisttag(), x.getDept());
           log.info("billmonth:{}. disttag:{}. sendtodept:{} bill finished", x.getBillMonth(), x.getDisttag(), x.getDept());
       }
       return new CmdResVo(0,"更新成功");
   }

    @Override
    public CmdResVo updateOtherFee(String usrid, OtherFeeVo otherFee)
    {
        if(otherFee == null || ObjectUtils.isNull(otherFee.getReportId()))
            return new CmdResVo(-1,"没有指定结算ID参数");

        FiBillReport fiBillReport = getById(otherFee.getReportId());
        if(fiBillReport == null)
            return new CmdResVo(-1,"结算ID不存在");

        if( ObjectUtils.isNotNull(fiBillReport.getBillStatus()) &&
                fiBillReport.getBillStatus() == 1)
            return new CmdResVo(-1,"已结账，不能修改");
        BeanUtils.copyProperties(otherFee, fiBillReport);

        if( ObjectUtils.isNull(fiBillReport.getCommissionAmt()))
            fiBillReport.setCommissionAmt(BigDecimal.ZERO);
        fiBillReport.setBillAmt(
                fiBillReport.getCommissionAmt().subtract(ObjectUtils.isNull( fiBillReport.getPlatFee())? BigDecimal.ZERO : fiBillReport.getPlatFee())
                        .subtract(ObjectUtils.isNull(fiBillReport.getTelFee())? BigDecimal.ZERO :fiBillReport.getTelFee())
                        .subtract(ObjectUtils.isNull(fiBillReport.getSmsFee())? BigDecimal.ZERO :fiBillReport.getSmsFee())
                        .subtract(ObjectUtils.isNull(fiBillReport.getQmFee())? BigDecimal.ZERO :fiBillReport.getQmFee())
                        .subtract(ObjectUtils.isNull(fiBillReport.getOtherFee1())? BigDecimal.ZERO :fiBillReport.getOtherFee1())
                        .subtract(ObjectUtils.isNull(fiBillReport.getOtherFee2())? BigDecimal.ZERO :fiBillReport.getOtherFee2())
                        .subtract(ObjectUtils.isNull(fiBillReport.getOtherFee3())? BigDecimal.ZERO :fiBillReport.getOtherFee3())
                        );
        fiBillReport.setMddt(new Date());
        fiBillReport.setMdusr(usrid);
        updateById(fiBillReport);
        return new CmdResVo(1,"更新成功");
    }

    @Override
    public CmdResVo refreshBillReport(String usrid, String billMonth)
    {
        try {
            //获取当前催员结算的最后记录时间。
            String refreshMonth = billMonth;
            if(StringUtils.isEmpty(billMonth)){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                refreshMonth = sdf.format( new Date());
            }
            log.info("billReport.更新佣金结算表..." + refreshMonth);
            Long ret = baseMapper.updateBillReport(usrid, refreshMonth);
            log.info("billReport.更新佣金记录：" + ret);
            return new CmdResVo(0,"更新成功" );
        }catch(Exception e)
        {
            log.error("billReport 更新佣金结算表 refresh Report exception: " + e );
            return new CmdResVo(-1,"Exception :" +e);
        }
    }

    @Override
    public CmdResVo saveAsExcel(String usrid, FiBIllListReqVo paras, HttpServletResponse response) {

        int pagesize = paras.getPageSize();
        if (pagesize > JPubUtils.exportMaxCount) {
            paras.setPageSize(JPubUtils.exportMaxCount);
        }

        IPage<FiBillResVo> pages=getBillReport(paras);
        ArrayList arr=new ArrayList();

        String exptempid=JPubUtils.getExpTempID(paras.getExpfilename(),"催收佣金统计表");
        String filename=JPubUtils.getExpFileName(
                paras.getExpfilename(),exptempid
        );

        pages.convert(u->{
            HashMap map=JPubUtils.toExportMap(u);
            if(map!=null) arr.add(map);
            return u;
        });
        CmdResVo resVo=exportService.ToExcel(
                response,
                arr,
                paras.getExpidlist(),
                paras.getExpnamelist(),
                filename,
                usrid
        );

        int okcount=resVo.getCount();
        if(okcount>0){
            fiImportHistService.AddExportHist(
                    resVo.getKeyId(),
                    usrid,
                    exptempid,
                    filename,
                    okcount
            );
        }

        return resVo;
    }
}




